package com.boss.thirteen.controller;


import com.boss.api.dto.ApiResultDTO;
import com.boss.common.base.BasicinfoBaseController;
import com.boss.common.entity.PageDTO;
import com.boss.common.service.ICommonService;
import com.boss.common.util.PageUtils;
import com.boss.framework.dto.PaginationDTO;
import com.boss.salary.entity.OperrateLogs;
import com.boss.salary.service.IOperrateLogsService;
import com.boss.salary.service.IRedisService;
import com.boss.sys.ca.user.dto.UserDTO;
import com.boss.sys.utils.SysUtils;
import com.boss.thirteen.entity.ThirteenAgencyVerify;
import com.boss.thirteen.service.IThirteenSalaryEndService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.http.MediaType;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/thirteenSalaryEndController", produces = MediaType.APPLICATION_JSON_VALUE)
public class ThirteenSalaryEndController extends BasicinfoBaseController {

    /**
     * 引入日志框架常量
     */
    private final static Logger logger = LoggerFactory.getLogger(ThirteenSalaryEndController.class);
    public final static String Executing = "Executing";
    @Autowired
    private IThirteenSalaryEndService iSalaryHistoryService;
    @Autowired
    private ICommonService iCommonService;
    @Autowired
    private IOperrateLogsService iOperrateLogsService;
    @Autowired
    private IRedisService redisService;

    /**
     * 十三月结
     * @return
     */
    @PostMapping("/saveMonthEnd")
    public ApiResultDTO saveMonthEnd(@RequestHeader("X-Token") String tokenid,@RequestBody List<ThirteenAgencyVerify> agencyVerifies) throws Exception {
            UserDTO userDTO = getUser(tokenid);
        try {
            Map<String,String> requestMap=new HashMap<>();
            Object re=redisService.get(userDTO.getProvince()+"thirteenLunarKnot");

            //查询缓存中该区划是否有在执行的生成操作
            if(!SysUtils.isNullOrEmpty(re)){
                String uuid="2021-"+userDTO.getProvince()+"-thirteenLunarKnot";
                requestMap.put("guid",uuid);
                requestMap.put("已执行年结操作，请稍后刷新查看",Executing);
                return ApiResultDTO.success(requestMap);
            }

            redisService.put(userDTO.getProvince()+"thirteenLunarKnot", 1);//添加执行控制，避免重复操作
            //添加操作日志
            OperrateLogs operrateLogs= new OperrateLogs();
            operrateLogs.setMofDivCode(userDTO.getProvince());
            operrateLogs.setTokenId(tokenid);
            operrateLogs.setUserAgencyId(userDTO.getAgency());
            operrateLogs.setUeserName(userDTO.getName());
            operrateLogs.setOperateName("十三月--年结--结");
            iOperrateLogsService.saveOperrateLogs(operrateLogs);
            String province = userDTO.getProvince();
            Map<String,String> map =iSalaryHistoryService.saveMonthEnd(province, agencyVerifies);
            return ApiResultDTO.success(map);
        } catch (Exception e) {

            redisService.del(userDTO.getProvince()+"thirteenLunarKnot");
            logger.error("年结时发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "年结失败");
        }
    }
    /**
     * 查看十三月结进度
     * @param uuid
     * @return
     */
    @GetMapping("/getPaymentPercent")
    public ApiResultDTO  getPaymentPercent(@RequestParam(value = "uuid") String uuid){
        try {
            Object re = redisService.get(uuid);

            if ("S".equals(re) || (re != null && re.toString().startsWith("F"))) {
                redisService.del(uuid);
                Object generateSalaryState = redisService.get(uuid);
                if(generateSalaryState!=null) {
                    redisService.del(uuid);
                }
            }
            return ApiResultDTO.success(re);
        }catch (Exception e) {
            e.printStackTrace();
            logger.error("十三月结失败", e.getMessage());
            return ApiResultDTO.error(ERROR_RSCODE, e.getMessage());
        }
    }
    /**
     * 撤销十三月结前校验
     * @param agencyIds
     * @param year
     * @return
     */
    @PostMapping("/checkRevokeMonthEnd")
    public ApiResultDTO checkRevokeMonthEnd(@RequestHeader("X-Token") String tokenid,@RequestParam("agencyIds") List<String> agencyIds, @RequestParam("year") String year) {
        try {
            UserDTO userDTO = getUser(tokenid);
            Map<String, Object> result = iSalaryHistoryService.checkRevokeMonthEnd(userDTO,agencyIds,year);
            return ApiResultDTO.success(result);
        } catch (Exception e) {
            logger.error("撤销十三月结时发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "撤销十三月结失败");
        }
    }

    /**
     * 撤销十三月结
     * @param agencyVerifyLists
     * @return
     */
    @PostMapping("/revokeMonthEnd")
    public ApiResultDTO revokeMonthEnd(@RequestHeader("X-Token") String tokenid,@RequestBody List<ThirteenAgencyVerify> agencyVerifyLists) {
        try {
            UserDTO userDTO = getUser(tokenid);
            //添加操作日志
//            OperrateLogs operrateLogs= new OperrateLogs();
//            operrateLogs.setMofDivCode(userDTO.getProvince());
//            operrateLogs.setTokenId(tokenid);
//            operrateLogs.setUserAgencyId(userDTO.getAgency());
//            operrateLogs.setUeserName(userDTO.getName());
//            operrateLogs.setOperateName("十三月工资--撤销年结");
//            operrateLogs.setAgencyId(agencyVerifyLists.get(0).getAgencyId());
//            iOperrateLogsService.saveOperrateLogs(operrateLogs);
            iSalaryHistoryService.revokeMonthEnd(userDTO.getProvince(),agencyVerifyLists);
            return ApiResultDTO.success(null, "撤销年结成功");
        } catch (Exception e) {
            logger.error("撤销年结时发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "撤销年结失败");
        }
    }



    /**
     * 获取十三月结的数据-分页
     * @return
     */
    @GetMapping("/getSalaryMonthEndPage")
    public ApiResultDTO getSalaryMonthEndPage(@RequestHeader("X-Token")String tokenid,
                                              @RequestParam(value = "page") String page,
                                              @RequestParam(value = "limit") String limit,
                                              @RequestParam(value = "agencyId") String agencyId){
        try {
            String province=getUser(tokenid).getProvince();
            UserDTO userDTO = getUser(tokenid);
            List<String> childrenIds = iCommonService.getAgencyChildrenId(userDTO, agencyId,tokenid);
            Map<String, Object> queryParam =new HashMap<>();
            queryParam.put("province",province);
            queryParam.put("is_pay_data_created","1");
            PaginationDTO paginationDTO = PageUtils.buildPaginationDTOPage(page,limit);
            PageDTO<Map<String,Object>> pageDTO = iSalaryHistoryService.getSalaryMonthEndPage(paginationDTO, queryParam, childrenIds);
            return ApiResultDTO.success(pageDTO,null);
        } catch (Exception e) {
            logger.error("获取十三月的数据发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "获取十三月的数据发生异常");
        }
    }

    /**
     * 获取十三月的数据-分页
     * @return
     */
    @GetMapping("/getSalaryMonthHistoryPage")
    public ApiResultDTO getSalaryMonthHistoryPage(@RequestHeader("X-Token")String tokenid,
                                                  @RequestParam(value = "page") String page,
                                                  @RequestParam(value = "limit") String limit,
                                                  @RequestParam(value = "agencyId") String agencyId,
                                                  @RequestParam(value = "year") String year){
        try {
            UserDTO userDTO = getUser(tokenid);
            List<String> childrenIds = iCommonService.getAgencyChildrenId(userDTO, agencyId,tokenid);
            Map<String, Object> queryParam =new HashMap<>();
            queryParam.put("year", year);
            queryParam.put("province",userDTO.getProvince());
            PaginationDTO paginationDTO = PageUtils.buildPaginationDTOPage(page,limit);
            PageDTO<Map<String,Object>> pageDTO = iSalaryHistoryService.getSalaryMonthHistoryPage(paginationDTO, queryParam, childrenIds);
            return ApiResultDTO.success(pageDTO,null);
        } catch (Exception e) {
            logger.error("获取十三月结的数据发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "获取十三月结的数据发生异常");
        }
    }

}
